<template>
  <div class="role-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入角色名称或描述"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd" v-if="userStore.hasPermission('role:create')">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        :data="roleList"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
              :disabled="!userStore.hasPermission('role:update')"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              v-if="userStore.hasPermission('role:update')"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handlePermissions(row)"
              v-if="userStore.hasPermission('role:update')"
            >
              权限
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleMenus(row)"
              v-if="userStore.hasPermission('role:update')"
            >
              菜单
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              v-if="userStore.hasPermission('role:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 角色表单对话框 -->
    <RoleForm
      v-model:visible="formVisible"
      :role-data="currentRole"
      @success="handleFormSuccess"
    />

    <!-- 权限分配对话框 -->
    <RolePermissions
      v-model:visible="permissionsVisible"
      :role-data="currentRole"
      @success="handleFormSuccess"
    />

    <!-- 菜单分配对话框 -->
    <RoleMenus
      v-model:visible="menusVisible"
      :role-data="currentRole"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getRoleList,
  deleteRole,
  updateRoleStatus,
  type Role
} from '@/api/role'
import RoleForm from './components/RoleForm.vue'
import RolePermissions from './components/RolePermissions.vue'
import RoleMenus from './components/RoleMenus.vue'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const roleList = ref<Role[]>([])
const formVisible = ref(false)
const permissionsVisible = ref(false)
const menusVisible = ref(false)
const currentRole = ref<Role | null>(null)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 获取角色列表
async function fetchRoleList() {
  loading.value = true
  try {
    const response = await getRoleList({
      page: pagination.page,
      page_size: pagination.pageSize,
      keyword: searchForm.keyword
    })

    roleList.value = response.list
    pagination.total = response.total
  } catch (error) {
    console.error('Failed to fetch role list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  pagination.page = 1
  fetchRoleList()
}

// 重置
function handleReset() {
  searchForm.keyword = ''
  pagination.page = 1
  fetchRoleList()
}

// 新增角色
function handleAdd() {
  currentRole.value = null
  formVisible.value = true
}

// 编辑角色
function handleEdit(role: Role) {
  currentRole.value = role
  formVisible.value = true
}

// 权限分配
function handlePermissions(role: Role) {
  currentRole.value = role
  permissionsVisible.value = true
}

// 菜单分配
function handleMenus(role: Role) {
  currentRole.value = role
  menusVisible.value = true
}

// 状态切换
async function handleStatusChange(role: Role) {
  try {
    await updateRoleStatus(role.id, role.status)
    ElMessage.success(`角色 "${role.name}" 状态更新成功`)
  } catch (error) {
    // 恢复原状态
    role.status = role.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败，请稍后重试')
    console.error('Failed to update role status:', error)
  }
}

// 删除角色
async function handleDelete(role: Role) {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteRole(role.id)
    ElMessage.success('删除成功')
    fetchRoleList()
  } catch (error) {
    // 用户取消删除
  }
}

// 表单成功回调
function handleFormSuccess() {
  fetchRoleList()
}

// 分页大小改变
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.page = 1
  fetchRoleList()
}

// 当前页改变
function handleCurrentChange(page: number) {
  pagination.page = page
  fetchRoleList()
}

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-management {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  margin-bottom: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  overflow: hidden;
}

.pagination {
  margin-top: 16px;
  text-align: right;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

:deep(.el-table) {
  width: 100%;
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}
</style>
